package com.hk.core.web;

import com.hk.commons.util.StringUtils;
import jakarta.servlet.ReadListener;
import jakarta.servlet.ServletInputStream;
import lombok.RequiredArgsConstructor;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Objects;


/**
 * @author Kevin
 */
@RequiredArgsConstructor
public class PostServletInputStream extends ServletInputStream {

    private ByteArrayInputStream inputStream;

    private final String body;

    private InputStream acquireInputStream() {
        if (Objects.isNull(inputStream)) {
            var bytes = StringUtils.isEmpty(body) ? new byte[0]
                    : body.getBytes(StandardCharsets.UTF_8);
            inputStream = new ByteArrayInputStream(bytes);
        }
        return inputStream;
    }

    @Override
    public boolean isFinished() {
        return false;
    }

    @Override
    public boolean markSupported() {
        return acquireInputStream().markSupported();
    }

    @Override
    public void close() throws IOException {
        try {
            if (inputStream != null) {
                inputStream.close();
            }
        } finally {
            inputStream = null;
        }
    }

    @Override
    public synchronized void mark(int readLimit) {
        acquireInputStream().mark(readLimit);
    }

    @Override
    public synchronized void reset() throws IOException {
        acquireInputStream().reset();
    }

    @Override
    public boolean isReady() {
        return false;
    }

    @Override
    public void setReadListener(ReadListener readListener) {
        // ignore
    }

    @Override
    public int read() throws IOException {
        return acquireInputStream().read();
    }
}
